{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Recommender Systems"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook we'll explore a \"deep learning\" approach to building a recommender system.  I say that in quotes because this particular application doesn't actually involve a \"deep\" network at all.  However, it does take advantage of the power of a modern computation framework like Keras to implement a recommender that performs at a very high level with minimal code.  We'll try a couple different approaches using a technique called [collaborative filtering](https://en.wikipedia.org/wiki/Collaborative_filtering).  Finally we'll build a true neural network and see how it compares to the collaborative filtering approach.\n",
    "\n",
    "The data used for this task is the [MovieLens](http://files.grouplens.org/datasets/movielens/ml-latest-small.zip) data set.  This content is inspired by the work Jeremy Howard did in his first [fast.ai course](https://course.fast.ai/).\n",
    "\n",
    "I've already saved the zip file to a local directory so we can get started with some imports and reading in the ratings.csv file, which is where the data for this task comes from."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "\n",
    "PATH = '/home/paperspace/data/ml-latest-small/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>userId</th>\n",
       "      <th>movieId</th>\n",
       "      <th>rating</th>\n",
       "      <th>timestamp</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>31</td>\n",
       "      <td>2.5</td>\n",
       "      <td>1260759144</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>1029</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1260759179</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>1061</td>\n",
       "      <td>3.0</td>\n",
       "      <td>1260759182</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>1129</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1260759185</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>1172</td>\n",
       "      <td>4.0</td>\n",
       "      <td>1260759205</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   userId  movieId  rating   timestamp\n",
       "0       1       31     2.5  1260759144\n",
       "1       1     1029     3.0  1260759179\n",
       "2       1     1061     3.0  1260759182\n",
       "3       1     1129     2.0  1260759185\n",
       "4       1     1172     4.0  1260759205"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ratings = pd.read_csv(PATH + 'ratings.csv')\n",
    "ratings.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data is tabular and consists of a user ID, a movie ID, and a rating (there's also a timestamp but we won't use it for this task).  Our task is to predict the rating for a user/movie pair, with the idea that if we had a model that's good at this task then we could predict how a user would rate movies they haven't seen yet and recommend movies with the highest predicted rating.\n",
    "\n",
    "The zip file also includes a listing of movies and their associated genres.  We don't actually need this for the model but it's useful to know about."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>movieId</th>\n",
       "      <th>title</th>\n",
       "      <th>genres</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>Toy Story (1995)</td>\n",
       "      <td>Adventure|Animation|Children|Comedy|Fantasy</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>Jumanji (1995)</td>\n",
       "      <td>Adventure|Children|Fantasy</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>Grumpier Old Men (1995)</td>\n",
       "      <td>Comedy|Romance</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>Waiting to Exhale (1995)</td>\n",
       "      <td>Comedy|Drama|Romance</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>Father of the Bride Part II (1995)</td>\n",
       "      <td>Comedy</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   movieId                               title  \\\n",
       "0        1                    Toy Story (1995)   \n",
       "1        2                      Jumanji (1995)   \n",
       "2        3             Grumpier Old Men (1995)   \n",
       "3        4            Waiting to Exhale (1995)   \n",
       "4        5  Father of the Bride Part II (1995)   \n",
       "\n",
       "                                        genres  \n",
       "0  Adventure|Animation|Children|Comedy|Fantasy  \n",
       "1                   Adventure|Children|Fantasy  \n",
       "2                               Comedy|Romance  \n",
       "3                         Comedy|Drama|Romance  \n",
       "4                                       Comedy  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "movies = pd.read_csv(PATH + 'movies.csv')\n",
    "movies.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a better sense of what the data looks like, we can turn it into a table by selecting the top 15 users/movies from the data and joining them together.  The result shows how each of the top users rated each of the top movies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>movieId</th>\n",
       "      <th>1</th>\n",
       "      <th>110</th>\n",
       "      <th>260</th>\n",
       "      <th>296</th>\n",
       "      <th>318</th>\n",
       "      <th>356</th>\n",
       "      <th>480</th>\n",
       "      <th>527</th>\n",
       "      <th>589</th>\n",
       "      <th>593</th>\n",
       "      <th>608</th>\n",
       "      <th>1196</th>\n",
       "      <th>1198</th>\n",
       "      <th>1270</th>\n",
       "      <th>2571</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>userId</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>2.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>73</th>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>212</th>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>213</th>\n",
       "      <td>3.0</td>\n",
       "      <td>2.5</td>\n",
       "      <td>5.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.5</td>\n",
       "      <td>2.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>294</th>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>311</th>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>2.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>380</th>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>452</th>\n",
       "      <td>3.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>468</th>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.0</td>\n",
       "      <td>2.5</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>509</th>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>547</th>\n",
       "      <td>3.5</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.5</td>\n",
       "      <td>2.0</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>564</th>\n",
       "      <td>4.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>580</th>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.5</td>\n",
       "      <td>4.0</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>624</th>\n",
       "      <td>5.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>NaN</td>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "movieId  1     110   260   296   318   356   480   527   589   593   608   \\\n",
       "userId                                                                      \n",
       "15        2.0   3.0   5.0   5.0   2.0   1.0   3.0   4.0   4.0   5.0   5.0   \n",
       "30        4.0   5.0   4.0   5.0   5.0   5.0   4.0   5.0   4.0   4.0   5.0   \n",
       "73        5.0   4.0   4.5   5.0   5.0   5.0   4.0   5.0   3.0   4.5   4.0   \n",
       "212       3.0   5.0   4.0   4.0   4.5   4.0   3.0   5.0   3.0   4.0   NaN   \n",
       "213       3.0   2.5   5.0   NaN   NaN   2.0   5.0   NaN   4.0   2.5   2.0   \n",
       "294       4.0   3.0   4.0   NaN   3.0   4.0   4.0   4.0   3.0   NaN   NaN   \n",
       "311       3.0   3.0   4.0   3.0   4.5   5.0   4.5   5.0   4.5   2.0   4.0   \n",
       "380       4.0   5.0   4.0   5.0   4.0   5.0   4.0   NaN   4.0   5.0   4.0   \n",
       "452       3.5   4.0   4.0   5.0   5.0   4.0   5.0   4.0   4.0   5.0   5.0   \n",
       "468       4.0   3.0   3.5   3.5   3.5   3.0   2.5   NaN   NaN   3.0   4.0   \n",
       "509       3.0   5.0   5.0   5.0   4.0   4.0   3.0   5.0   2.0   4.0   4.5   \n",
       "547       3.5   NaN   NaN   5.0   5.0   2.0   3.0   5.0   NaN   5.0   5.0   \n",
       "564       4.0   1.0   2.0   5.0   NaN   3.0   5.0   4.0   5.0   5.0   5.0   \n",
       "580       4.0   4.5   4.0   4.5   4.0   3.5   3.0   4.0   4.5   4.0   4.5   \n",
       "624       5.0   NaN   5.0   5.0   NaN   3.0   3.0   NaN   3.0   5.0   4.0   \n",
       "\n",
       "movieId  1196  1198  1270  2571  \n",
       "userId                           \n",
       "15        5.0   4.0   5.0   5.0  \n",
       "30        4.0   5.0   5.0   3.0  \n",
       "73        5.0   5.0   5.0   4.5  \n",
       "212       NaN   3.0   3.0   5.0  \n",
       "213       5.0   3.0   3.0   4.0  \n",
       "294       4.0   4.5   4.0   4.5  \n",
       "311       3.0   4.5   4.5   4.0  \n",
       "380       4.0   NaN   3.0   5.0  \n",
       "452       4.0   4.0   4.0   2.0  \n",
       "468       3.0   3.5   3.0   3.0  \n",
       "509       5.0   5.0   3.0   4.5  \n",
       "547       2.5   2.0   3.5   3.5  \n",
       "564       5.0   5.0   3.0   3.0  \n",
       "580       4.0   3.5   3.0   4.5  \n",
       "624       5.0   5.0   5.0   2.0  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g = ratings.groupby('userId')['rating'].count()\n",
    "top_users = g.sort_values(ascending=False)[:15]\n",
    "\n",
    "g = ratings.groupby('movieId')['rating'].count()\n",
    "top_movies = g.sort_values(ascending=False)[:15]\n",
    "\n",
    "top_r = ratings.join(top_users, rsuffix='_r', how='inner', on='userId')\n",
    "top_r = top_r.join(top_movies, rsuffix='_r', how='inner', on='movieId')\n",
    "\n",
    "pd.crosstab(top_r.userId, top_r.movieId, top_r.rating, aggfunc=np.sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To build our first collaborative filtering model, we need to take care of a few steps first.  The user/movie fields are currently non-sequential integers representing some unique ID for that entity.  We need them to be sequential starting at zero to use for modeling (you'll see why later).  We can use scikit-learn's LabelEncoder class to transform the fields.  We'll also create variables with the total number of unique users and movies in the data, as well as the min and max ratings present in the data, for reasons that will become apparent shortly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(671, 9066, 0.5, 5.0)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_enc = LabelEncoder()\n",
    "ratings['user'] = user_enc.fit_transform(ratings['userId'].values)\n",
    "n_users = ratings['user'].nunique()\n",
    "\n",
    "item_enc = LabelEncoder()\n",
    "ratings['movie'] = item_enc.fit_transform(ratings['movieId'].values)\n",
    "n_movies = ratings['movie'].nunique()\n",
    "\n",
    "ratings['rating'] = ratings['rating'].values.astype(np.float32)\n",
    "min_rating = min(ratings['rating'])\n",
    "max_rating = max(ratings['rating'])\n",
    "\n",
    "n_users, n_movies, min_rating, max_rating"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a traditional (X, y) pairing of data and label, then split the data into training and test data sets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((90003, 2), (10001, 2), (90003,), (10001,))"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = ratings[['user', 'movie']].values\n",
    "y = ratings['rating'].values\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)\n",
    "\n",
    "X_train.shape, X_test.shape, y_train.shape, y_test.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another constant we'll need for the model is the number of factors per user/movie.  This number can be whatever we want, however for the collaborative filtering model it does need to be the same size for both users and movies.  In his class, Jeremy said he played around with different numbers and 50 seemed to work best so we'll go with that.\n",
    "\n",
    "Finally, we need to turn users and movies into separate arrays in the training and test data.  This is because in Keras they'll each be defined as distinct inputs, and the way Keras works is each input needs to be fed in as its own array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_factors = 50\n",
    "\n",
    "X_train_array = [X_train[:, 0], X_train[:, 1]]\n",
    "X_test_array = [X_test[:, 0], X_test[:, 1]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we get to the model itself.  The main idea here is we're going to use embeddings to represent each user and each movie in the data.  These embeddings will be vectors (of size n_factors) that start out as random numbers but are fit by the model to capture the essential qualities of each user/movie.  We can accomplish this by computing the dot product between a user vector and a movie vector to get a predicted rating.  The code is fairly simple, there isn't even a traditional neural network layer or activation involved.  I stuck some regularization on the embedding layers and used a different initializer but even that probably isn't necessary.  Notice that this is where we need the number of unique users and movies, since those are required to define the size of each embedding matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n",
      "/home/paperspace/anaconda3/envs/fastai/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n",
      "  return f(*args, **kwds)\n"
     ]
    }
   ],
   "source": [
    "from keras.models import Model\n",
    "from keras.layers import Input, Reshape, Dot\n",
    "from keras.layers.embeddings import Embedding\n",
    "from keras.optimizers import Adam\n",
    "from keras.regularizers import l2\n",
    "\n",
    "def RecommenderV1(n_users, n_movies, n_factors):\n",
    "    user = Input(shape=(1,))\n",
    "    u = Embedding(n_users, n_factors, embeddings_initializer='he_normal',\n",
    "                  embeddings_regularizer=l2(1e-6))(user)\n",
    "    u = Reshape((n_factors,))(u)\n",
    "    \n",
    "    movie = Input(shape=(1,))\n",
    "    m = Embedding(n_movies, n_factors, embeddings_initializer='he_normal',\n",
    "                  embeddings_regularizer=l2(1e-6))(movie)\n",
    "    m = Reshape((n_factors,))(m)\n",
    "    \n",
    "    x = Dot(axes=1)([u, m])\n",
    "\n",
    "    model = Model(inputs=[user, movie], outputs=x)\n",
    "    opt = Adam(lr=0.001)\n",
    "    model.compile(loss='mean_squared_error', optimizer=opt)\n",
    "\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is kind of a neat example of how flexible and powerful modern computation frameworks like Keras and PyTorch are.  Even though these are billed as deep learning libraries, they have the building blocks to quickly create any computation graph you want and get automatic differentiation essentially for free.  Below you can see that all of the parameters are in the embedding layers, we don't have any traditional neural net components at all."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "__________________________________________________________________________________________________\n",
      "Layer (type)                    Output Shape         Param #     Connected to                     \n",
      "==================================================================================================\n",
      "input_1 (InputLayer)            (None, 1)            0                                            \n",
      "__________________________________________________________________________________________________\n",
      "input_2 (InputLayer)            (None, 1)            0                                            \n",
      "__________________________________________________________________________________________________\n",
      "embedding_1 (Embedding)         (None, 1, 50)        33550       input_1[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "embedding_2 (Embedding)         (None, 1, 50)        453300      input_2[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "reshape_1 (Reshape)             (None, 50)           0           embedding_1[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "reshape_2 (Reshape)             (None, 50)           0           embedding_2[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "dot_1 (Dot)                     (None, 1)            0           reshape_1[0][0]                  \n",
      "                                                                 reshape_2[0][0]                  \n",
      "==================================================================================================\n",
      "Total params: 486,850\n",
      "Trainable params: 486,850\n",
      "Non-trainable params: 0\n",
      "__________________________________________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = RecommenderV1(n_users, n_movies, n_factors)\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's go ahead and train this for a few epochs and see what we get."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 90003 samples, validate on 10001 samples\n",
      "Epoch 1/5\n",
      "90003/90003 [==============================] - 6s 66us/step - loss: 9.7935 - val_loss: 3.4641\n",
      "Epoch 2/5\n",
      "90003/90003 [==============================] - 4s 49us/step - loss: 2.0427 - val_loss: 1.6521\n",
      "Epoch 3/5\n",
      "90003/90003 [==============================] - 4s 49us/step - loss: 1.1574 - val_loss: 1.3535\n",
      "Epoch 4/5\n",
      "90003/90003 [==============================] - 4s 48us/step - loss: 0.9027 - val_loss: 1.2607\n",
      "Epoch 5/5\n",
      "90003/90003 [==============================] - 4s 48us/step - loss: 0.7786 - val_loss: 1.2209\n"
     ]
    }
   ],
   "source": [
    "history = model.fit(x=X_train_array, y=y_train, batch_size=64, epochs=5,\n",
    "                    verbose=1, validation_data=(X_test_array, y_test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not bad for a first try.  We can make some improvements though.  The first thing we can do is add a \"bias\" to each embedding.  The concept is similar to the bias in a fully-connected layer or the intercept in a linear model.  It just provides an extra degree of freedom.  We can implement this idea using new embedding layers with a vector length of one.  The bias embeddings get added to the result of the dot product.\n",
    "\n",
    "The second improvement we can make is running the output of the dot product through a sigmoid layer and then scaling the result using the min and max ratings in the data.  This is a neat technique that introduces a non-linearity into the output and results in a modest performance bump.\n",
    "\n",
    "I also refactored the code a bit by pulling out the embedding layer and reshape operation into a separate class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.layers import Add, Activation, Lambda\n",
    "\n",
    "class EmbeddingLayer:\n",
    "    def __init__(self, n_items, n_factors):\n",
    "        self.n_items = n_items\n",
    "        self.n_factors = n_factors\n",
    "    \n",
    "    def __call__(self, x):\n",
    "        x = Embedding(self.n_items, self.n_factors, embeddings_initializer='he_normal',\n",
    "                      embeddings_regularizer=l2(1e-6))(x)\n",
    "        x = Reshape((self.n_factors,))(x)\n",
    "        return x\n",
    "\n",
    "def RecommenderV2(n_users, n_movies, n_factors, min_rating, max_rating):\n",
    "    user = Input(shape=(1,))\n",
    "    u = EmbeddingLayer(n_users, n_factors)(user)\n",
    "    ub = EmbeddingLayer(n_users, 1)(user)\n",
    "    \n",
    "    movie = Input(shape=(1,))\n",
    "    m = EmbeddingLayer(n_movies, n_factors)(movie)\n",
    "    mb = EmbeddingLayer(n_movies, 1)(movie)\n",
    "\n",
    "    x = Dot(axes=1)([u, m])\n",
    "    x = Add()([x, ub, mb])\n",
    "    x = Activation('sigmoid')(x)\n",
    "    x = Lambda(lambda x: x * (max_rating - min_rating) + min_rating)(x)\n",
    "\n",
    "    model = Model(inputs=[user, movie], outputs=x)\n",
    "    opt = Adam(lr=0.001)\n",
    "    model.compile(loss='mean_squared_error', optimizer=opt)\n",
    "\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model summary shows the new graph.  Notice the additional embedding layers with parameter numbers equal to the unique user and movie counts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "__________________________________________________________________________________________________\n",
      "Layer (type)                    Output Shape         Param #     Connected to                     \n",
      "==================================================================================================\n",
      "input_3 (InputLayer)            (None, 1)            0                                            \n",
      "__________________________________________________________________________________________________\n",
      "input_4 (InputLayer)            (None, 1)            0                                            \n",
      "__________________________________________________________________________________________________\n",
      "embedding_3 (Embedding)         (None, 1, 50)        33550       input_3[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "embedding_5 (Embedding)         (None, 1, 50)        453300      input_4[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "reshape_3 (Reshape)             (None, 50)           0           embedding_3[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "reshape_5 (Reshape)             (None, 50)           0           embedding_5[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "embedding_4 (Embedding)         (None, 1, 1)         671         input_3[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "embedding_6 (Embedding)         (None, 1, 1)         9066        input_4[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "dot_2 (Dot)                     (None, 1)            0           reshape_3[0][0]                  \n",
      "                                                                 reshape_5[0][0]                  \n",
      "__________________________________________________________________________________________________\n",
      "reshape_4 (Reshape)             (None, 1)            0           embedding_4[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "reshape_6 (Reshape)             (None, 1)            0           embedding_6[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "add_1 (Add)                     (None, 1)            0           dot_2[0][0]                      \n",
      "                                                                 reshape_4[0][0]                  \n",
      "                                                                 reshape_6[0][0]                  \n",
      "__________________________________________________________________________________________________\n",
      "activation_1 (Activation)       (None, 1)            0           add_1[0][0]                      \n",
      "__________________________________________________________________________________________________\n",
      "lambda_1 (Lambda)               (None, 1)            0           activation_1[0][0]               \n",
      "==================================================================================================\n",
      "Total params: 496,587\n",
      "Trainable params: 496,587\n",
      "Non-trainable params: 0\n",
      "__________________________________________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = RecommenderV2(n_users, n_movies, n_factors, min_rating, max_rating)\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 90003 samples, validate on 10001 samples\n",
      "Epoch 1/5\n",
      "90003/90003 [==============================] - 6s 64us/step - loss: 1.2850 - val_loss: 0.9083\n",
      "Epoch 2/5\n",
      "90003/90003 [==============================] - 5s 57us/step - loss: 0.7445 - val_loss: 0.7801\n",
      "Epoch 3/5\n",
      "90003/90003 [==============================] - 5s 57us/step - loss: 0.5615 - val_loss: 0.7646\n",
      "Epoch 4/5\n",
      "90003/90003 [==============================] - 5s 57us/step - loss: 0.4273 - val_loss: 0.7669\n",
      "Epoch 5/5\n",
      "90003/90003 [==============================] - 5s 58us/step - loss: 0.3298 - val_loss: 0.7823\n"
     ]
    }
   ],
   "source": [
    "history = model.fit(x=X_train_array, y=y_train, batch_size=64, epochs=5,\n",
    "                    verbose=1, validation_data=(X_test_array, y_test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Those two additions to the model resulted in a pretty sizable improvement.  Validation error is now down to ~0.76 which is about as good as what Jeremy got (and I believe close to SOTA for this data set).\n",
    "\n",
    "That pretty much covers the conventional approach to solving this problem, but there's another way we can tackle this.  Instead of taking the dot product of the embedding vectors, what if we just concatenated the embeddings together and stuck a fully-connected layer on top of them?  It's still not technically \"deep\" but it would at least be a neural network!  To modify the code, we can remove the bias embeddings from V2 and do a concat on the embedding layers instead.  Then we can add some dropout, insert a dense layer, and stick some dropout on the dense layer as well.  Finally, we'll run it through a single-unit dense layer keep the sigmoid trick at the end."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.layers import Concatenate, Dense, Dropout\n",
    "\n",
    "def RecommenderNet(n_users, n_movies, n_factors, min_rating, max_rating):\n",
    "    user = Input(shape=(1,))\n",
    "    u = EmbeddingLayer(n_users, n_factors)(user)\n",
    "    \n",
    "    movie = Input(shape=(1,))\n",
    "    m = EmbeddingLayer(n_movies, n_factors)(movie)\n",
    "    \n",
    "    x = Concatenate()([u, m])\n",
    "    x = Dropout(0.05)(x)\n",
    "    \n",
    "    x = Dense(10, kernel_initializer='he_normal')(x)\n",
    "    x = Activation('relu')(x)\n",
    "    x = Dropout(0.5)(x)\n",
    "    \n",
    "    x = Dense(1, kernel_initializer='he_normal')(x)\n",
    "    x = Activation('sigmoid')(x)\n",
    "    x = Lambda(lambda x: x * (max_rating - min_rating) + min_rating)(x)\n",
    "\n",
    "    model = Model(inputs=[user, movie], outputs=x)\n",
    "    opt = Adam(lr=0.001)\n",
    "    model.compile(loss='mean_squared_error', optimizer=opt)\n",
    "\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most of the parameters are still in the embedding layers, but we have some added learning capability from the dense layers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "__________________________________________________________________________________________________\n",
      "Layer (type)                    Output Shape         Param #     Connected to                     \n",
      "==================================================================================================\n",
      "input_5 (InputLayer)            (None, 1)            0                                            \n",
      "__________________________________________________________________________________________________\n",
      "input_6 (InputLayer)            (None, 1)            0                                            \n",
      "__________________________________________________________________________________________________\n",
      "embedding_7 (Embedding)         (None, 1, 50)        33550       input_5[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "embedding_8 (Embedding)         (None, 1, 50)        453300      input_6[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "reshape_7 (Reshape)             (None, 50)           0           embedding_7[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "reshape_8 (Reshape)             (None, 50)           0           embedding_8[0][0]                \n",
      "__________________________________________________________________________________________________\n",
      "concatenate_1 (Concatenate)     (None, 100)          0           reshape_7[0][0]                  \n",
      "                                                                 reshape_8[0][0]                  \n",
      "__________________________________________________________________________________________________\n",
      "dropout_1 (Dropout)             (None, 100)          0           concatenate_1[0][0]              \n",
      "__________________________________________________________________________________________________\n",
      "dense_1 (Dense)                 (None, 10)           1010        dropout_1[0][0]                  \n",
      "__________________________________________________________________________________________________\n",
      "activation_2 (Activation)       (None, 10)           0           dense_1[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "dropout_2 (Dropout)             (None, 10)           0           activation_2[0][0]               \n",
      "__________________________________________________________________________________________________\n",
      "dense_2 (Dense)                 (None, 1)            11          dropout_2[0][0]                  \n",
      "__________________________________________________________________________________________________\n",
      "activation_3 (Activation)       (None, 1)            0           dense_2[0][0]                    \n",
      "__________________________________________________________________________________________________\n",
      "lambda_2 (Lambda)               (None, 1)            0           activation_3[0][0]               \n",
      "==================================================================================================\n",
      "Total params: 487,871\n",
      "Trainable params: 487,871\n",
      "Non-trainable params: 0\n",
      "__________________________________________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model = RecommenderNet(n_users, n_movies, n_factors, min_rating, max_rating)\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 90003 samples, validate on 10001 samples\n",
      "Epoch 1/5\n",
      "90003/90003 [==============================] - 6s 71us/step - loss: 0.9461 - val_loss: 0.8079\n",
      "Epoch 2/5\n",
      "90003/90003 [==============================] - 6s 64us/step - loss: 0.8097 - val_loss: 0.7898\n",
      "Epoch 3/5\n",
      "90003/90003 [==============================] - 6s 63us/step - loss: 0.7781 - val_loss: 0.7855\n",
      "Epoch 4/5\n",
      "90003/90003 [==============================] - 6s 64us/step - loss: 0.7617 - val_loss: 0.7820\n",
      "Epoch 5/5\n",
      "90003/90003 [==============================] - 6s 63us/step - loss: 0.7513 - val_loss: 0.7858\n"
     ]
    }
   ],
   "source": [
    "history = model.fit(x=X_train_array, y=y_train, batch_size=64, epochs=5,\n",
    "                    verbose=1, validation_data=(X_test_array, y_test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Without doing any tuning at all we still managed to get a result that's pretty close to the best performance we saw with the traditional approach.  This technique has the added benefit that we can easily incorporate additional features into the model.  For instance, we could create some date features from the timestamp or throw in the movie genres as a new embedding layer.  We could tune the size of the movie and user embeddings independently since they no longer need to match.  Lots of possibilites here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
